package com.itmuch.usercenter.controller.user;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.itmuch.usercenter.auth.CheckLogin;
import com.itmuch.usercenter.domain.dto.user.JwtTokenRespDto;
import com.itmuch.usercenter.domain.dto.user.LoginRespDto;
import com.itmuch.usercenter.domain.dto.user.UserLoginDto;
import com.itmuch.usercenter.domain.dto.user.UserRespDto;
import com.itmuch.usercenter.domain.entity.user.User;
import com.itmuch.usercenter.service.user.UserService;
import com.itmuch.usercenter.util.JwtOperator;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.Map;

/**
 * @author caiqian
 * @date 2021/5/7 8:36
 */
@RestController
@RequestMapping("users")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Slf4j
public class UserController {

  private final UserService userService;
  private final WxMaService wxMaService;
  private final JwtOperator jwtOperator;

  @GetMapping("/{id}")
  @CheckLogin
  public User findById(@PathVariable Integer id) {
    return this.userService.findById(id);
  }

  @GetMapping("/gen-token")
  public String gentoken() {
    Map<String, Object> userInfo = new HashMap<>(3);
    userInfo.put("id", 1);
    userInfo.put("wxNickName", "大门");
    userInfo.put("roles", "user");

    return jwtOperator.generateToken(userInfo);
  }

  @PostMapping("/login")
  public LoginRespDto login(@RequestBody UserLoginDto loginDto) throws WxErrorException {

    //微信小程序服务端校验是否已经成功登录的结果
    WxMaJscode2SessionResult result = this.wxMaService.getUserService()
        .getSessionInfo(loginDto.getCode());

    //这是微信的openid, 用户在微信这边的唯一标识
    String openid = result.getOpenid();

    //看用户是否注册，如果没有注册就注册
    //如果已经注册，就颁发token
    User user = this.userService.login(loginDto, openid);

    //颁发token
    Map<String, Object> userInfo = new HashMap<>(3);
    userInfo.put("id", user.getId());
    userInfo.put("wxNickName", user.getWxNickname());
    userInfo.put("roles", user.getRoles());

    String token = this.jwtOperator.generateToken(userInfo);
    log.info("用户[{}]登录成功,token:[{}],过期时间：{}", user.getWxNickname(), token,
        this.jwtOperator.getExpirationDateFromToken(token));

    return LoginRespDto.builder()
        .user(
            UserRespDto.builder()
                .id(user.getId())
                .avatarUrl(user.getAvatarUrl())
                .bouns(user.getBonus())
                .wxNickName(user.getWxNickname())
                .build()
        )
        .token(
            JwtTokenRespDto.builder()
                .token(token)
                .expirationTime(jwtOperator.getExpirationDateFromToken(token).getTime())
                .build()
        )
        .build();
  }
}
